const express = require("express");
const cors = require("cors");
const app = express();
const router = express.Router();
const path = require("path");
const template = require("express-art-template");
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");

const paySocket = require("./socket/paySocket") 

// 引入配置文件
const config  = require("./config") 

const io = new Server(server,{
  cors:true
});

io.of(config.sockets.pay).on("connection", function (socket) {
  console.log("链接到 pay 服务器");
  paySocket.socket = socket;
});


// 配置跨域
app.use(cors({
   origin:config.origin,
   credentials:true
})); 



// 配置 session
const session = require("express-session");
app.use(session({
  secret:config.secret, // 签发 SessionID 的密匙
  resave:false,
  saveUninitialized:true,
  cookie:{  // sessionID 这个 Cookie 相关的设置
        secure:false
  }
}));
 
// 引入日志记录插件
const log4js = require("log4js");

const logger = log4js.getLogger();

log4js.configure({
  appenders: { cheese: { type: "file", filename: "jwxt.log" } },
  // 这里的 level 一般设置为 error 即可 这里为了记录更多的信息 设置了 debug
  categories: { default: { appenders: ["cheese"], level: "debug" } }
});

// 链接数据库
require("./model/connect");

// 设置模板
app.engine("html",template);
app.set("view options",{
      debug:true 
});
app.set("views",path.join(__dirname,"views"));
app.set("view engine","html");


// 配置静态资源
app.use(express.static(path.join(__dirname,"views")))
app.use("/uploads",express.static(path.join(__dirname,"uploads")))
app.use(express.json())
app.use(express.urlencoded({extended:true}))

// 使用路由
app.use("/api",router)
router.use("/student",require("./router/studentRouter"));
router.use("/actively",require("./router/activelyRouter"));
router.use("/admin",require("./router/adminRouter"));
router.use("/dean",require("./router/deanRouter"));
router.use("/department",require("./router/departmentRouter"));
router.use("/grade",require("./router/gradeRouter"));
router.use("/order",require("./router/orderRouter"));
router.use("/postman",require("./router/postmanRouter"));
router.use("/subject",require("./router/subjectRouter"));
router.use("/teacher",require("./router/teacherRouter"));
router.use("/pay",require("./router/payRouter"));
router.use(require("./router/loginRouter"))

server.listen(config.port, config.host , () => {
  logger.debug("staring server ....")
  logger.debug("listening on *:"+config.port)
});